 
  

 






<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do;jsessionid=4FCCB481C702D708A7360133D128E359?Id=83 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:27:36 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
<head>
 <title>
  Java Practices -> Get size of object in memory
 </title>
 <link rel="stylesheet" type="text/css" href="../stylesheet8.css" media="all">
 
 <link rel="shortcut icon" href='../images/favicon.ico' type="image/vnd.microsoft.icon">
 <meta name="description" content="Concise presentations of java programming practices, tasks, and conventions, amply illustrated with syntax highlighted code examples.">
 
 <meta name='keywords' content='measure,optimisation,optimization,performance,size,java,java programming,java practices,java idiom,java style,java design patterns,java coding conventions,'>
 
 
</head>
 
<body>


<div class='menu-bar'>
 
  <a href='../home/HomeAction.html' title='Table of Contents'>Home</a> |
  <a href='../vote/VoteSummaryAction-2.html' title='View Poll Results'>Poll</a> |
   
  <A href='../feedback/FeedbackAction451f-2.html?Operation=Show' title='Send Your Feedback'>Wiki</a> |
  <b><a href='../source/SourceAction-2.html' title='Grab Source Code'>Source Code</a></b><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |

  <a href='http://www.web4j.com/Java_Web_Application_Framework_Overview.jsp?From=1' title='Free Download - Java Web Application Framework'><b>WEB4J</b></a> |
  
  <a href='http://www.date4j.net/' title='Replacement for java.util.Date'><b>DATE4J</b></a> |

   <a href='../references/ReferencesAction-2.html' title='References'>Links</a>
   
  <form action='http://www.javapractices.com/search/SearchAction.do' method='get' class='search-form'>
   <input type='text' name='SearchTerms' value="" size=12 maxlength=50 class='search'>
   <input type='submit' value="Search">
  </form>
 
</div>

<P>



  

 






<p class="display-messages">

 

 

</p>


<div class="main-layout">
 
   

 




<div class='page-title'>Get size of object in memory</div>

<div class='main-body'>
 
<br>
Here is a utility which can estimate the size of an object in memory,
if the object has a no-argument constructor. It follows the style used
by <i>Java Platform Performance</i>, by Wilson and Kesselman. Given a class name, it 
will build a number of objects using the no-argument constructor, and measure the 
effect on JVM memory use. <em>Thus, it measures the size of 'empty' objects containing no data.</em> 

<P>To measure the size of a particular object containing data, a similar technique can easily be used: 
measure JVM memory use before and after building the object.

<P>
In addition, JDK 1.5 has added an 
<a href="http://java.sun.com/javase/6/docs/api/java/lang/instrument/Instrumentation.html">Instrumentation</a> 
interface, which 
includes a method named <a href="http://java.sun.com/javase/6/docs/api/java/lang/instrument/Instrumentation.html#getObjectSize(java.lang.Object)">getObjectSize</a> method. 
However, this method seems to be intended for tool makers.
<br>
<PRE>

<span class='comment'>/**
* Measures the approximate size of an object in memory, given a Class which
* has a no-argument constructor.
*/</span>
<span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>class</span> ObjectSizer {

  <span class='comment'>/**
  * First and only argument is the package-qualified name of a class
  * which has a no-argument constructor.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>void</span> main(String... aArguments){
    Class theClass = <span class='keyword'>null</span>;
    <span class='keyword'>try</span> {
      theClass = Class.forName(aArguments[<span class='literal'>0</span>]);
    }
    <span class='keyword'>catch</span> (Exception ex) {
      System.err.println(<span class='literal'>"Cannot build a Class object: "</span> + aArguments[<span class='literal'>0</span>]);
      System.err.println(<span class='literal'>"Use a package-qualified name, and check classpath."</span>);
    }
    <span class='keyword'>long</span> size = ObjectSizer.getObjectSize( theClass );
    System.out.println(<span class='literal'>"Approximate size of "</span> + theClass + <span class='literal'>" objects :"</span> + size);
  }


  <span class='comment'>/**
  * Return the approximate size in bytes, and return zero if the class
  * has no default constructor.
  *
  * @param aClass refers to a class which has a no-argument constructor.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>long</span> getObjectSize( Class aClass ){
    <span class='keyword'>long</span> result = <span class='literal'>0</span>;

    <span class='comment'>//if the class does not have a no-argument constructor, then
</span>    <span class='comment'>//inform the user and return 0.
</span>    <span class='keyword'>try</span> {
      aClass.getConstructor( <span class='keyword'>new</span> Class[]{} );
    }
    <span class='keyword'>catch</span> ( NoSuchMethodException ex ) {
      System.err.println(aClass + <span class='literal'>" does not have a no-argument constructor."</span>);
      <span class='keyword'>return</span> result;
    }

    <span class='comment'>//this array will simply hold a bunch of references, such that
</span>    <span class='comment'>//the objects cannot be garbage-collected
</span>    Object[] objects = <span class='keyword'>new</span> Object[fSAMPLE_SIZE];

    <span class='comment'>//build a bunch of identical objects
</span>    <span class='keyword'>try</span> {
      Object throwAway = aClass.newInstance();

      <span class='keyword'>long</span> startMemoryUse = getMemoryUse();
      <span class='keyword'>for</span> (<span class='keyword'>int</span> idx=<span class='literal'>0</span>; idx &lt; objects.length ; ++idx) {
        objects[idx] = aClass.newInstance();
      }
      <span class='keyword'>long</span> endMemoryUse = getMemoryUse();

      <span class='keyword'>float</span> approximateSize = ( endMemoryUse - startMemoryUse ) /<span class='literal'>100f</span>;
      result = Math.round( approximateSize );
    }
    <span class='keyword'>catch</span> (Exception ex) {
      System.err.println(<span class='literal'>"Cannot create object using "</span> + aClass);
    }
    <span class='keyword'>return</span> result;
  }

  <span class='comment'>// PRIVATE //
</span>  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>int</span> fSAMPLE_SIZE = <span class='literal'>100</span>;
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>long</span> fSLEEP_INTERVAL = <span class='literal'>100</span>;

  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>long</span> getMemoryUse(){
    putOutTheGarbage();
    <span class='keyword'>long</span> totalMemory = Runtime.getRuntime().totalMemory();

    putOutTheGarbage();
    <span class='keyword'>long</span> freeMemory = Runtime.getRuntime().freeMemory();

    <span class='keyword'>return</span> (totalMemory - freeMemory);
  }

  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>void</span> putOutTheGarbage() {
    collectGarbage();
    collectGarbage();
  }

  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>void</span> collectGarbage() {
    <span class='keyword'>try</span> {
      System.gc();
      Thread.currentThread().sleep(fSLEEP_INTERVAL);
      System.runFinalization();
      Thread.currentThread().sleep(fSLEEP_INTERVAL);
    }
    <span class='keyword'>catch</span> (InterruptedException ex){
      ex.printStackTrace();
    }
  }
} 
</PRE>
<br>
<p><tt>ObjectSizer</tt> can be easily placed in an interactive console
application.
<p>An example run gives :
<p><tt>>java -cp . Console ObjectSizeInterpreter</tt>
<br><tt>Please enter a class name>java.blah</tt>
<br><tt>Invalid.&nbsp; Example:"java.lang.String">java.util.ArrayList</tt>
<br><tt>Approximate size of class java.util.ArrayList objects in bytes:
80</tt>
<br><tt>Please enter a class name>java.util.Vector</tt>
<br><tt>Approximate size of class java.util.Vector objects in bytes: 80</tt>
<br><tt>Please enter a class name>java.util.HashMap</tt>
<br><tt>Approximate size of class java.util.HashMap objects in bytes: 104</tt>
<br><tt>Please enter a class name>java.lang.Long</tt>
<br><tt>class java.lang.Long does not have a no-argument constructor.</tt>
<br><tt>Please enter a class name>exit</tt>
<p><tt>Bye.</tt>
<p>Here is the Interpreter class :
<br>
<PRE>

<span class='keyword'>import</span> java.util.*;
<span class='keyword'>import</span> java.text.MessageFormat;

<span class='comment'>/**
* Given a package-qualified class name, return the approximate size of
* the object in bytes.
*/</span>
<span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>class</span> ObjectSizeInterpreter <span class='keyword'>implements</span> Interpreter {

  <span class='comment'>/**
  * @param aLine is a non-null, package-qualified name of a class.
  * @param aResult is a non-null, empty List which acts as an "out"
  * parameter; when returned, aResult must contain a non-null, non-empty
  * List containing a description of the size of the object.
  *
  * @return true only if the user has requested to quit the Interpreter.
  * @exception IllegalArgumentException if a param does not comply.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>boolean</span> parseInput (String  aLine, <span class='keyword'>final</span> List aResult) {
    <span class='keyword'>if</span> ( aResult == <span class='keyword'>null</span> ) {
      <span class='keyword'>throw</span> <span class='keyword'>new</span> IllegalArgumentException(<span class='literal'>"Result param cannot be null."</span>);
    }
    <span class='keyword'>if</span> ( !aResult.isEmpty() ){
      <span class='keyword'>throw</span> <span class='keyword'>new</span> IllegalArgumentException(<span class='literal'>"Result param must be empty."</span>);
    }
    <span class='keyword'>if</span> ( aLine == <span class='keyword'>null</span> ) {
      <span class='keyword'>throw</span> <span class='keyword'>new</span> IllegalArgumentException(<span class='literal'>"Line must not be null."</span>);
    }

    <span class='keyword'>boolean</span> hasRequestedQuit = aLine.trim().equalsIgnoreCase(fQUIT) ||
                               aLine.trim().equalsIgnoreCase(fEXIT);
    <span class='keyword'>if</span> ( hasRequestedQuit ) {
      <span class='comment'>//display only a blank line
</span>      aResult.add(fNEW_LINE);
    }
    <span class='keyword'>else</span> {
      <span class='keyword'>try</span> {
        Class theClass = Class.forName(aLine);
        <span class='keyword'>long</span> size = ObjectSizer.getObjectSize( theClass );
        <span class='keyword'>if</span> ( size &gt; <span class='literal'>0</span> ){
          Object[] insertedData = {theClass, <span class='keyword'>new</span> Long(size) };
          MessageFormat sizeMessage = <span class='keyword'>new</span> MessageFormat(fPATTERN);
          String message = sizeMessage.format( insertedData );
          aResult.add( message );
          aResult.add( fNEW_LINE );
        }
        aResult.add( fDEFAULT_PROMPT );
      }
      <span class='keyword'>catch</span> (ClassNotFoundException ex){
        <span class='comment'>//recover by asking the user for corrected input
</span>        aResult.clear();
        aResult.add(fERROR_PROMPT);
      }
    }

    <span class='keyword'>if</span> ( aResult.isEmpty() ) {
      <span class='keyword'>throw</span> <span class='keyword'>new</span> IllegalStateException(<span class='literal'>"Result must be non-empty."</span>);
    }
    <span class='keyword'>return</span> hasRequestedQuit;
  }

  <span class='comment'>/**
  * Return the text to be displayed upon start-up of the Interpreter.
  */</span>
  <span class='keyword'>public</span> String getHelloPrompt() {
    <span class='keyword'>return</span> fHELLO_PROMPT;
  }

  <span class='comment'>/// PRIVATE /////
</span>  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> String fHELLO_PROMPT = <span class='literal'>"Please enter a class name&gt;"</span>;
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> String fDEFAULT_PROMPT = <span class='literal'>"Please enter a class name&gt;"</span>;
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> String fERROR_PROMPT = <span class='literal'>"Invalid.  Example:&#092;"java.lang.String&#092;"&gt;"</span>;
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> String fPATTERN = <span class='literal'>"Approximate size of {0} objects in bytes: {1}"</span>;
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> String fQUIT = <span class='literal'>"quit"</span>;
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> String fEXIT = <span class='literal'>"exit"</span>;
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> String fNEW_LINE = System.getProperty(<span class='literal'>"line.separator"</span>);
} 
</PRE>
<br>
<br>
<br>

</div>




<div class='topic-section'>See Also :</div>
<div class='main-body'>
 
  
  <a href='TopicAction8240-2.html?Id=36'>Measure application performance</a> <br>
 
  
  <a href='TopicAction83bb-2.html?Id=79'>Console input</a> <br>
 
</div>


<div class='topic-section'>Would you use this technique?</div>
<div class='main-body'>
  
  <form action="http://www.javapractices.com/vote/AddVoteAction.do" method='post'>
    Yes<input type='radio' name='Choice' value='Y' >
    &nbsp;&nbsp;No<input type='radio' name='Choice' value='N'>
    &nbsp;&nbsp;Undecided<input type='radio' name='Choice' value="?" >
    &nbsp;&nbsp;<input type=submit value="Vote" >
    <input type='hidden' name='Operation' value='Apply'>
    <input type='hidden' name='TopicId' value='83'>
  </form>
</div>

<div style='height:10.0em;'></div>

 
 
</div>

  

 





<div align='center' class='legalese'>  
&copy; 2011 Hirondelle Systems |
<a href='../source/SourceAction-2.html'><b>Source Code</b></a><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |
<a href="mailto:webmaster@javapractices.com">Contact</a> |
<a href="http://creativecommons.org/licenses/by-nc-sa/1.0/">License</a> |
<a href='../apps/cjp.rss'>RSS</a>
<!-- ukey="2AC36CD2" -->
<!-- ckey="16DF3D87" -->
<br>

 Individual code snippets can be used under this <a href='../LICENSE.txt'>BSD license</a> - Last updated on June 6, 2010.<br>
 Over 150,000 unique IPs last month - <span title='Java Practices 2.6.5, Mon May 16 00:00:00 EDT 2011'>Built with</span> <a href='http://www.web4j.com/'>WEB4J</a>.<br>
 - In Memoriam : Bill Dirani -
</div>

<script src="../../www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-2633428-1";
urchinTracker();
</script>



</body>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do;jsessionid=4FCCB481C702D708A7360133D128E359?Id=83 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:27:36 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
</html>
